import config from '@/config'
import {
	getToken
} from '@/utils/auth'
import errorCode from '@/config/errorCode'
import toast from '@/plugins/toast.js'

const timeout = 10000
const baseUrl = config.baseUrl

const upload = config => {
	config.header = config.header || {}
	if (getToken()) {
		config.header['token'] = getToken()
	}
	return new Promise((resolve, reject) => {
		uni.showLoading({
			title: '上传中'
		})
		uni.uploadFile({
			timeout: timeout,
			url: baseUrl + '/app-api/infra/file/upload',
			filePath: config.filePath || '',
			name: config.name || 'file',
			header: config.header,
			formData: config.formData || '',
			success: res => {
				uni.hideLoading()
				let result = JSON.parse(res.data)
				const code = result.code || 200
				const msg = errorCode[code] || result.msg || errorCode['default']
				if (code === 200) {
					resolve(result)
				} else if (code == 401) {
					reject('无效的会话，或者会话已过期，请重新登录。')
				} else if (code === 500) {
					toast.msg(msg)
					reject('500')
				} else if (code !== 200) {
					toast.msg(msg)
					reject(code)
				}
			},
			fail: error => {
				uni.hideLoading()
				let {
					message
				} = error
				if (message && message == 'Network Error') {
					message = '后端接口连接异常'
				} else if (message && message.includes('timeout')) {
					message = '系统接口请求超时'
				} else if (message && message.includes('Request failed with status code')) {
					message = '系统接口' + message.substr(message.length - 3) + '异常'
				} else {
					message = '后端接口连接异常'
				}
				toast.msg(message)
				reject(error)
			}
		})
	})
}

export default upload